import { useState } from "react";

export default function TaskList({ todos, onChangeTodo, onDeleteTodo }) {
  return (
    <div>
      <ul>
        {todos.map((todo) => (
          <li key={todo.id}>
            <Task todo={todo} onChange={onChangeTodo} onDelete={onDeleteTodo}></Task>
          </li>
        ))}
      </ul>
    </div>
  );
}

function Task({ todo, onChange, onDelete }) {
  const [isEdit, setIsEdit] = useState(true);
  let todoContent;
  if (isEdit) {
    todoContent = (
      <>
        {todo.title}
        <button onClick={() => setIsEdit(!isEdit)}>edit</button>
      </>
    );
  } else {
    todoContent = (
      <>
        <input
          value={todo.title}
          onChange={(e) => onChange({ ...todo, title: e.target.value })}
        ></input>
        <button onClick={() => setIsEdit(!isEdit)}>save</button>
      </>
    );
  }
  return (
    <>
      <label>
        <input
          type="checkbox"
          onChange={(e) =>
            onChange({
              ...todo,
              done: e.target.value,
            })
          }
          checked={todo.done}
        ></input>
        {todoContent}
        <button
          onClick={() => {
            onDelete(todo.id);
          }}
        >
          Delete
        </button>
      </label>
    </>
  );
}
